<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model="searchForm"
      :items="formItems"
      :show-expand="true"
      @search="handleSearch"
      @reset="resetSearchParams"
    />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap>
            <ElButton type="primary" :icon="Plus" @click="handleAdd"> 新增已认证人员 </ElButton>
            <!-- <ArtExcelImport @import-success="handleImportSuccess" @import-error="handleImportError">
              <template #import-text> 导入 </template>
            </ArtExcelImport> -->
            <el-upload 
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            accept=".xlsx,xls"
            >
           <ElButton type="primary"  @click="handleImport"> 导入excel </ElButton>
          </el-upload>
            <ElButton type="primary" :icon="Download" @click="handleDownLoad"> 下载 </ElButton>
            <!-- <ArtExcelDownLoad
              style="margin-left: 10px"
              filename="已认证人员数据"
              type="success"
              :headers="headers"
              @export-success="handleExportSuccess"
              @export-error="handleExportError"
            >
              下载
            </ArtExcelDownLoad> -->
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 认证状态 -->
        <template #authStatus="{ row }">
          <DictTag
            :dict-type="'10025'"
            :value="row.authStatus"
            :fallback-text="getAuthStatusText(row.recordStatus)"
            :auto-tag-type="true"
          />
        </template>

        <!-- 所属平台 -->
        <template #newPlatform="{ row }">
          <DictTag
            :dict-type="'10020'"
            :value="row.newPlatform"
            :fallback-text="getPlatformText(row.newPlatform)"
            :auto-tag-type="true"
          />
        </template>
      </ArtTable>

      <!-- 新增/编辑对话框 -->
      <AuthPersonnelEditDialog
        v-model="editDialogVisible"
        :user-data="currentUserData"
        :is-view="isViewMode"
        @success="handleDialogSuccess"
      />

      <!-- 核实对话框 -->
      <ElDialog
        v-model="checkDialogVisible"
        title="核实身份"
        width="500px"
        :close-on-click-modal="false"
      >
        <ElForm ref="checkFormRef" :model="checkForm" :rules="checkFormRules" label-width="100px">
          <ElFormItem label="认证状态" prop="authStatus">
            <ElSelect v-model="checkForm.authStatus" placeholder="请选择认证状态">
              <ElOption label="待核实" :value="10025" />
              <ElOption label="已核实" :value="10026" />
              <ElOption label="核实失败" :value="10027" />
            </ElSelect>
          </ElFormItem>
        </ElForm>
        
        <template #footer>
          <ElSpace>
            <ElButton @click="checkDialogVisible = false">取消</ElButton>
            <ElButton type="primary" @click="handleCheckSubmit" :loading="checkLoading">
              确定
            </ElButton>
          </ElSpace>
        </template>
      </ElDialog>

    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, h } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Upload, Download } from '@element-plus/icons-vue'
  import { useTable } from '@/composables/useTable'
  import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import AuthPersonnelEditDialog from './modules/auth-personnel-edit-dialog.vue'
  import {
    openApiNewAuthUserPageDataUsingPost,
    openApiNewAuthUserDelDataUsingPost,
    openApiNewAuthUserCheckUsingPost,
    openApiNewAuthUserImportExcelUsingPost,
    openApiNewAuthUserDownloadExcelUsingGet
  } from '@/api/neWyirenzhengrenyuan'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import * as XLSX from 'xlsx'
  import { DictTag, DictSelect } from '@/components/core/dics/index.vue'

  // 类型定义
  interface SearchForm {
    newPlatform?: number | null
    newIdentity?: string
  }

  interface ButtonMoreItem {
    key: string
    label: string
  }

  interface NewAuthUserVo {
    id?: number
    newName?: string
    newIdentity?: string
    authStatus?: number
    newPlatform?: number
    [key: string]: any
  }

  // 响应式数据
  const searchForm = ref<SearchForm>({
    newPlatform: null,
    newIdentity: ''
  })

  const editDialogVisible = ref(false)
  const currentUserData = ref<NewAuthUserVo | null>(null)
  const isViewMode = ref(false)

  // 核实对话框
  const checkDialogVisible = ref(false)
  const checkFormRef = ref()
  const checkLoading = ref(false)
  const checkForm = ref({
    id: undefined as number | undefined,
    authStatus: undefined as number | undefined
  })
  const checkFormRules = {
    authStatus: [{ required: true, message: '请选择认证状态', trigger: 'change' }]
  }

  const handleDownLoad = async() => {
    try {
      window.location.href = 'http://d6f6869b.natappfree.cc/sgbApi/new/authUser/downloadExcel'
    } catch (error) {
      console.log(error,'错误原因');
    }
  }

  // const handleDownLoad = async() => {
  //   try {
  //   const downloadUrl = 'http://d6f6869b.natappfree.cc/sgbApi/new/authUser/downloadExcel';
    
  //   const newWindow = window.open(downloadUrl, '_blank');
  //   if (!newWindow) {
  //     // 若被浏览器拦截，提示用户允许弹出窗口
  //     ElMessage.warning('下载窗口可能被浏览器拦截，请允许弹出窗口后重试');
  //   }

  //   // const response = await fetch(downloadUrl, {
  //   //   method: 'GET',
  //   //   credentials: 'include', // 携带Cookie（跨域时需要后端允许）
  //   //   // 若需要Token，添加header：
  //   //   // headers: { Authorization: `Bearer ${token}` }
  //   // });
  //   // if (!response.ok) throw new Error('下载失败');
  //   // const blob = await response.blob();
  //   // const url = URL.createObjectURL(blob);
  //   // const link = document.createElement('a');
  //   // link.href = url;
  //   // link.download = '用户模板.xlsx';
  //   // link.click();
  //   // URL.revokeObjectURL(url); // 释放内存
  //   // ElMessage.success('文件开始下载');
  // } catch (error: any) {
  //   console.error('下载失败:', error);
  //   ElMessage.error(`下载失败：${error.message || '未知错误'}`);
  // }
  // }

  // 导入对话框
  const importDialogVisible = ref(false)
  const uploadRef = ref()
  const importFile = ref<File | null>(null)

  // 搜索表单配置
  const formItems = computed(() => [
    {
      key: 'newIdentity',
      label: '身份证号',
      type: 'input',
      props: {
        placeholder: '请输入身份证号',
        clearable: true
      }
    },
    {
      key: 'newPlatform',
      label: '所属平台',
      type: 'select',
      props: {
        placeholder: '请选择所属平台',
        clearable: true,
        options: [
          { label: '快递员', value: 10020 },
          { label: '外卖员', value: 10021 },
          { label: '网约车司机', value: 10022 },
          { label: '其他', value: 10023 }
        ]
      }
    }
  ])

  // 使用 useTable 管理表格数据
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: openApiNewAuthUserPageDataUsingPost,
      apiParams: {
        body: {
          newPlatform: searchForm.value.newPlatform,
          newIdentity: searchForm.value.newIdentity
        }
      },
      paginationWrapper: 'body',
      columnsFactory: () => [
        {
          prop: 'id',
          label: 'ID',
          width: 80
        },
        {
          prop: 'newName',
          label: '姓名'
        },
        {
          prop: 'newIdentity',
          label: '身份证号'
        },
        {
          prop: 'authStatus',
          label: '认证状态',
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        },
        {
          prop: 'newPlatform',
          label: '所属平台',
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 280,
          fixed: 'right',
          align: 'center',
          headerAlign: 'center',
          formatter: (row) => {
            return h('div', {}, [
              h(ArtButtonTable, {
                type: 'view',
                onClick: () => buttonMoreClick({ key: 'view', label: '查看' }, row),
                title: '查看'
              }),
              h(ArtButtonTable, {
                type: 'edit',
                onClick: () => buttonMoreClick({ key: 'edit', label: '编辑' }, row)
              }),
              h(ArtButtonTable, {
                type: 'more',
                onClick: () => buttonMoreClick({ key: 'check', label: '核实' }, row),
                title: '核实'
              }),
              h(ArtButtonTable, {
                type: 'delete',
                onClick: () => buttonMoreClick({ key: 'delete', label: '删除' }, row)
              })
            ])
          }
        }
      ]
    }
  })

  const showSearchBar = ref(false)

  const handleSearch = () => {
    searchParams.body.newPlatform = searchForm.value.newPlatform
    searchParams.body.newIdentity = searchForm.value.newIdentity
    getData()
  }

  const handleAdd = () => {
    currentUserData.value = null
    isViewMode.value = false
    editDialogVisible.value = true
  }
  const handleFileChange = (uploadFile) => {
const file = uploadFile.raw;
  if (file) {
    handleImport(file);  
  }
  }

  const handleImport = async (file: File) => {
  console.log('上传的文件信息:', file);
  
  // 1. 验证文件类型
  const isExcel = /\.(xlsx|xls)$/.test(file.name);
  if (!isExcel) {
    ElMessage.error("只能上传Excel文件（.xlsx 或 .xls）！");
    return;
  }

  try {
    // const arrayBuffer = await new Promise<ArrayBuffer>((resolve, reject) => {
    //   const reader = new FileReader();
    //   reader.onload = (e) => {
    //     const result = e.target?.result as ArrayBuffer;
    //     if (result) resolve(result);
    //     else reject(new Error('无法获取文件二进制数据'));
    //   };
    //   reader.onerror = () => reject(new Error(`文件读取失败: ${reader.error?.message || '未知错误'}`));
    //   reader.readAsArrayBuffer(file); // 读取为二进制流
    // });

    // const workbook = XLSX.read(arrayBuffer, { type: 'array' });
    // const firstSheetName = workbook.SheetNames[0];
    // if (!firstSheetName) {
    //   throw new Error('Excel文件中未找到工作表');
    // }
    // const worksheet = workbook.Sheets[firstSheetName];
    // const results = XLSX.utils.sheet_to_json(worksheet);
    // console.log('前端解析的Excel数据:', results); // 仅用于预览


    // FormData，传递原始文件二进制流给后端
    const formData = new FormData();
    // 直接append File对象（内部会自动处理二进制流）
    formData.append('file', file); 

    //调用接口，传递二进制流
    const response = await openApiNewAuthUserImportExcelUsingPost({
      body: formData, 
      headers: {
        'Content-Type': 'multipart/form-data' 
      }
    });
    console.log(response,669988);
    


    if (response) {
      ElMessage({
    message: '文件导入中，预计1-3分钟！',
    duration: 60000, 
  });

  
  setTimeout(() => {
    ElMessage.success('文件上传并导入成功');
    getData(); 
  }, 90000);
    } else {
      ElMessage.error(`导入失败`);
    }

  } catch (error: any) {
    ElMessage.error(`处理失败：${error.message || '网络错误'}`);
    console.error('导入过程出错:', error);
  }
};

  

  const buttonMoreClick = async (item: ButtonMoreItem, row: NewAuthUserVo) => {
    switch (item.key) {
      case 'view':
        currentUserData.value = row
        isViewMode.value = true
        editDialogVisible.value = true
        break
      case 'edit':
        currentUserData.value = row
        isViewMode.value = false
        editDialogVisible.value = true
        break
      case 'check':
        checkForm.value.id = row.id
        checkForm.value.authStatus = row.authStatus
        checkDialogVisible.value = true
        break
      case 'delete':
        await handleDelete(row)
        break
    }
  }

  const handleDelete = async (row: NewAuthUserVo) => {
    try {
      await ElMessageBox.confirm(`确定要删除用户"${row.newName}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await openApiNewAuthUserDelDataUsingPost({
        body: {
          id: row.id
        }
      })

      ElMessage.success('删除成功')
      getData()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  const handleCheckSubmit = async () => {
    if (!checkFormRef.value) return

    try {
      await checkFormRef.value.validate()
      checkLoading.value = true

      await openApiNewAuthUserCheckUsingPost({
        body: {
          id: checkForm.value.id,
          authStatus: checkForm.value.authStatus
        }
      })

      ElMessage.success('核实成功')
      checkDialogVisible.value = false
      getData()
    } catch (error) {
      console.error('核实失败:', error)
    } finally {
      checkLoading.value = false
    }
  }

  const handleDialogSuccess = () => {
    editDialogVisible.value = false
    currentUserData.value = null
    isViewMode.value = false
    getData()
  }

  // 认证状态文本
  const getAuthStatusText = (status?: number) => {
    const statusMap: Record<number, string> = {
      10025: '待核实',
      10026: '已核实',
      10027: '核实失败'
    }
    return statusMap[status || 0] || '未知'
  }

  // 所属平台文本
  const getPlatformText = (platform?: number) => {
    const platformMap: Record<number, string> = {
      10020: '快递员',
      10021: '外卖员',
      10022: '网约车司机',
      10023: '其他'
    }
    return platformMap[platform || 0] || '未知'
  }

  // 自定义表头映射
  const headers = {
    newName: '姓名',
    newIdentity: '身份证号',
    authStatus: '认证状态',
    newPlatform: '所属平台'
  }

</script>

<style lang="scss" scoped>
  .el-upload__tip {
    margin-top: 8px;
    color: #909399;
    font-size: 12px;
  }
</style>
